<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>智能教学助手</h2>
        <p>用户登录系统</p>
      </div>

      <div v-if="!isChangePassword" class="login-form">
        <!-- 用户角色选择 -->
        <div class="form-item user-role-section">
          <label>用户类型</label>
          <div class="user-role-options">
            <el-radio-group v-model="userRole" class="user-role-group">
              <el-radio :value="1">教师</el-radio>
              <el-radio :value="2">学生</el-radio>
              <el-radio :value="3">管理员</el-radio>
            </el-radio-group>
          </div>
        </div>

        <div class="form-item login-type" v-if="userRole === 1">
          <label>登录方式</label>
          <div class="login-type-options">
            <el-radio-group v-model="loginType" class="login-type-group">
              <el-radio :value="1">工号登录</el-radio>
              <el-radio :value="2">手机号登录</el-radio>
            </el-radio-group>
          </div>
        </div>

        <div class="form-item login-type" v-if="userRole === 2">
          <label>登录方式</label>
          <div class="login-type-options">
            <el-radio-group v-model="loginType" class="login-type-group">
              <el-radio :value="1">学号登录</el-radio>
              <el-radio :value="2">手机号登录</el-radio>
            </el-radio-group>
          </div>
        </div>

        <div class="form-item login-type" v-if="userRole === 3">
          <label>登录方式</label>
          <div class="login-type-options">
            <el-radio-group v-model="loginType" class="login-type-group">
              <el-radio :value="1">账号登录</el-radio>
              <el-radio :value="2">手机号登录</el-radio>
            </el-radio-group>
          </div>
        </div>

        <div class="form-item">
          <label>{{ getUserIdLabel() }}</label>
          <input
            type="text"
            v-model="loginForm.loginId"
            :placeholder="getLoginIdPlaceholder()"
          />
        </div>

        <div class="form-item">
          <label>密码</label>
          <div class="password-input">
            <input
              :type="showPassword ? 'text' : 'password'"
              v-model="loginForm.password"
              placeholder="请输入密码"
            />
            <span
              class="toggle-password"
              @click="showPassword = !showPassword"
            >
              <i :class="showPassword ? 'eye-open' : 'eye-close'"></i>
            </span>
          </div>
        </div>

        <div class="form-actions">
          <button
            class="primary-btn"
            @click="handleLogin"
            :disabled="isLoading"
          >
            {{ isLoading ? '登录中...' : '登录' }}
          </button>

          <div class="action-links">
            <a href="#" @click.prevent="forgotPassword">忘记密码?</a>
            <a href="#" @click.prevent="goToRegister" v-if="userRole === 1 || userRole === 2">注册账号</a>
          </div>
        </div>
      </div>

      <div v-else class="change-password-form">
        <div class="form-item">
          <label>旧密码</label>
          <input
            type="password"
            v-model="passwordForm.oldPassword"
            placeholder="请输入旧密码"
          />
        </div>

        <div class="form-item">
          <label>新密码</label>
          <input
            type="password"
            v-model="passwordForm.newPassword"
            placeholder="请输入新密码"
          />
        </div>

        <div class="form-item">
          <label>确认新密码</label>
          <input
            type="password"
            v-model="passwordForm.confirmPassword"
            placeholder="请再次输入新密码"
          />
        </div>

        <div class="form-actions">
          <button
            class="primary-btn"
            @click="handleChangePassword"
            :disabled="isLoading"
          >
            {{ isLoading ? '提交中...' : '修改密码' }}
          </button>

          <button
            class="secondary-btn"
            @click="isChangePassword = false"
          >
            返回登录
          </button>
        </div>
      </div>

      <div v-if="errorMessage" class="error-message">
        {{ errorMessage }}
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';

export default {
  name: 'LoginPage',
  setup() {
    const router = useRouter();
    const isLoading = ref(false);
    const errorMessage = ref('');
    const showPassword = ref(false);
    const isChangePassword = ref(false);
    const loginType = ref(1); // 默认工号登录
    const userRole = ref(1); // 默认教师角色，1-教师，2-学生，3-管理员

    const loginForm = reactive({
      loginId: '',
      password: '',
    });

    const passwordForm = reactive({
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    });

    // 根据用户角色获取登录ID标签
    const getUserIdLabel = () => {
      if (userRole.value === 1) { // 教师
        return loginType.value === 1 ? '教师工号' : '手机号';
      } else if (userRole.value === 2) { // 学生
        return loginType.value === 1 ? '学号' : '手机号';
      } else { // 管理员
        return loginType.value === 1 ? '管理员工号' : '手机号';
      }
    };

    // 根据用户角色获取登录ID占位符
    const getLoginIdPlaceholder = () => {
      if (userRole.value === 1) { // 教师
        return loginType.value === 1 ? '请输入教师工号' : '请输入手机号';
      } else if (userRole.value === 2) { // 学生
        return loginType.value === 1 ? '请输入学号' : '请输入手机号';
      } else { // 管理员
        return loginType.value === 1 ? '请输入管理员工号' : '请输入手机号';
      }
    };

    const handleLogin = async () => {
      // 表单验证
      if (!loginForm.loginId) {
        errorMessage.value = getUserIdLabel() + '不能为空';
        return;
      }

      if (!loginForm.password) {
        errorMessage.value = '请输入密码';
        return;
      }

      try {
        isLoading.value = true;
        errorMessage.value = '';

        // 清除可能存在的旧token
        localStorage.removeItem('token');
        localStorage.removeItem('userId');
        localStorage.removeItem('userName');
        localStorage.removeItem('userRole');
        localStorage.removeItem('tokenExpireTime');

        // 构造登录请求数据
        const loginData = {
          loginId: loginForm.loginId,
          password: loginForm.password,
          loginType: loginType.value,
          userRole: userRole.value
        };

        console.log('登录请求数据:', loginData);

        const response = await axios.post('/api/auth/login', loginData);

        if (response.data.success) {
          // 登录成功，保存token和用户信息
          const token = response.data.token;
          const expireTime = new Date().getTime() + 12 * 60 * 60 * 1000; // 12小时后过期
          const userData = response.data.user;

          // 保存token和过期时间
          localStorage.setItem('token', token);
          localStorage.setItem('tokenExpireTime', expireTime.toString());
          localStorage.setItem('userRole', userRole.value.toString());

          // 打印登录响应详情，帮助调试
          console.log('登录成功，响应数据:', response.data);

          // 根据用户角色保存不同信息
          if (userRole.value === 1) { // 教师
            // 检查响应数据结构，适配不同的API返回格式
            // 处理嵌套结构
            const teacherData = userData.teacher || userData;

            // 保存教师ID (优先使用 userId，其次是 teacherId)
            const teacherId = teacherData.userId || teacherData.teacherId || teacherData.id;
            if (teacherId) {
              localStorage.setItem('teacherId', teacherId);
              console.log('已保存教师ID:', teacherId);
            } else {
              console.error('警告：响应中未包含有效的教师ID:', teacherData);
            }

            // 保存教师姓名
            localStorage.setItem('teacherName', teacherData.name || '未知教师');

            // 保存教师学科信息
            if (teacherData.subject) {
              localStorage.setItem('teacherSubject', teacherData.subject);
              console.log('已保存教师学科:', teacherData.subject);
            } else {
              console.warn('响应中未包含教师学科信息');
              // 默认设置为数学，可以根据需求调整
              localStorage.setItem('teacherSubject', 'math');
              console.log('已设置默认学科: math');
            }

            // 登录成功提示
            const welcomeMessage = getUserRolePrefix() + response.data.user.name + '，欢迎回来！';
            alert(welcomeMessage);

            // 教师登录成功后直接跳转到教学设计页面
            router.push('/design/new').then(() => {
              // 在路由跳转完成后刷新页面
              window.location.reload();
            });
          } else if (userRole.value === 2) { // 学生
            localStorage.setItem('studentId', userData.userId || userData.studentId);
            localStorage.setItem('studentName', userData.name);
            
            // 学生登录成功后跳转到学生仪表盘
            router.push('/student/dashboard').then(() => {
              window.location.reload();
            });
          } else if (userRole.value === 3) { // 管理员
            localStorage.setItem('adminId', userData.userId || userData.adminId);
            localStorage.setItem('adminName', userData.name);
            
            // 管理员登录成功后跳转到管理员仪表盘
            router.push('/admin/dashboard').then(() => {
              window.location.reload();
            });
          }
        } else {
          errorMessage.value = response.data.message || '登录失败，请重试';
        }
      } catch (error) {
        console.error('登录错误:', error);
        if (error.response) {
          errorMessage.value = error.response.data?.message || `登录失败 (${error.response.status})`;
        } else if (error.request) {
          errorMessage.value = '服务器无响应，请检查网络连接';
        } else {
          errorMessage.value = '登录请求发送失败，请稍后重试';
        }
      } finally {
        isLoading.value = false;
      }
    };

    // 获取用户角色前缀
    const getUserRolePrefix = () => {
      if (userRole.value === 1) {
        return '';  // 教师无需特殊前缀
      } else if (userRole.value === 2) {
        return '同学';
      } else {
        return '管理员';
      }
    };

    const handleChangePassword = async () => {
      // 表单验证
      if (!passwordForm.oldPassword) {
        errorMessage.value = '请输入旧密码';
        return;
      }

      if (!passwordForm.newPassword) {
        errorMessage.value = '请输入新密码';
        return;
      }

      if (passwordForm.newPassword.length < 6) {
        errorMessage.value = '新密码长度不能少于6位';
        return;
      }

      if (passwordForm.newPassword !== passwordForm.confirmPassword) {
        errorMessage.value = '两次输入的新密码不一致';
        return;
      }

      try {
        isLoading.value = true;
        errorMessage.value = '';

        const response = await axios.post('/api/auth/change-password', {
          ...passwordForm,
          userRole: userRole.value // 添加用户角色信息
        }, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          }
        });

        if (response.data.success) {
          alert('密码修改成功，请重新登录');
          // 清空表单并返回登录页
          passwordForm.oldPassword = '';
          passwordForm.newPassword = '';
          passwordForm.confirmPassword = '';
          isChangePassword.value = false;
          // 清除token和用户信息
          localStorage.removeItem('token');
          localStorage.removeItem('teacherId');
          localStorage.removeItem('teacherName');
          localStorage.removeItem('studentId');
          localStorage.removeItem('studentName');
          localStorage.removeItem('adminId');
          localStorage.removeItem('adminName');
          localStorage.removeItem('userRole');
        } else {
          errorMessage.value = response.data.message || '密码修改失败，请重试';
        }
      } catch (error) {
        console.error('修改密码错误:', error);
        errorMessage.value = error.response?.data?.message || '操作失败，请稍后重试';
      } finally {
        isLoading.value = false;
      }
    };

    const forgotPassword = () => {
      alert('请联系系统管理员重置密码');
    };

    const goToRegister = () => {
      // 根据当前选择的角色跳转到注册页面
      if (userRole.value === 1 || userRole.value === 2) {
        router.push({
          path: '/register',
          query: { role: userRole.value } // 传递角色参数到注册页面
        });
      }
    };

    return {
      isLoading,
      errorMessage,
      showPassword,
      isChangePassword,
      loginType,
      userRole,
      loginForm,
      passwordForm,
      getUserIdLabel,
      getLoginIdPlaceholder,
      handleLogin,
      handleChangePassword,
      forgotPassword,
      goToRegister
    };
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.login-box {
  width: 400px;
  padding: 30px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  color: #333;
  margin-bottom: 5px;
}

.login-header p {
  color: #666;
  font-size: 16px;
}

.form-item {
  margin-bottom: 20px;
}

.form-item label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  color: #333;
}

.form-item input {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-item input:focus {
  border-color: #1890ff;
  outline: none;
}

.password-input {
  position: relative;
}

.toggle-password {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  color: #999;
}

.form-actions {
  margin-top: 24px;
}

.primary-btn {
  width: 100%;
  padding: 10px;
  background-color: #1890ff;
  border: none;
  border-radius: 4px;
  color: white;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.primary-btn:hover {
  background-color: #40a9ff;
}

.primary-btn:disabled {
  background-color: #1890ff;
  opacity: 0.7;
  cursor: not-allowed;
}

.secondary-btn {
  width: 100%;
  padding: 10px;
  background-color: #f5f5f5;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  color: rgba(0, 0, 0, 0.65);
  font-size: 16px;
  cursor: pointer;
  margin-top: 12px;
  transition: all 0.3s;
}

.secondary-btn:hover {
  background-color: #e6e6e6;
}

.forgot-password {
  text-align: center;
  margin-top: 16px;
}

.action-links {
  display: flex;
  justify-content: space-between;
  margin-top: 16px;
}

.action-links a {
  color: #1890ff;
  text-decoration: none;
}

.error-message {
  margin-top: 16px;
  color: #f5222d;
  text-align: center;
}

.eye-open::before {
  content: '👁️';
}

.eye-close::before {
  content: '👁️‍🗨️';
}

.login-type, .user-role-section {
  margin-bottom: 15px;
}

.login-type-options, .user-role-options {
  display: flex;
  justify-content: space-between;
  margin-top: 5px;
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid #e4e7ed;
}

.login-type-options span, .user-role-options span {
  flex: 1;
  text-align: center;
  padding: 8px 0;
  cursor: pointer;
  background: #f5f7fa;
  transition: all 0.3s;
}

.login-type-options span.active, .user-role-options span.active {
  background: #1a73e8;
  color: white;
}

.login-type-group, .user-role-group {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.login-type-group :deep(.el-radio), .user-role-group :deep(.el-radio) {
  margin-right: 20px;
  color: #333;
}

.login-type-group :deep(.el-radio__label), .user-role-group :deep(.el-radio__label) {
  font-size: 16px;
}

.login-type-group :deep(.el-radio__input.is-checked + .el-radio__label),
.user-role-group :deep(.el-radio__input.is-checked + .el-radio__label) {
  color: #1a73e8;
}
</style> 